package com.example.demo.ui.kotlin

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.entity.MultiItemEntity
import com.example.demo.R
import com.example.demo.bese.BaseActivity
import com.example.demo.databinding.ActivitySelectableBinding
import com.example.demo.ui.kotlin.adapter.OnItemsClickListener
import com.example.demo.ui.kotlin.adapter.SelectableIAdapter
import com.example.demo.ui.kotlin.adapter.SelectableItem
import com.example.demo.util.MyJson
import com.example.demo.util.ToastUtil
import com.orhanobut.logger.Logger

/**
 *
 * @author: xtxiaolu
 * @date: 2023/8/30
 * 描述: 使用kotlin实现多选列表，支持全选和取消
 * 可以根据自己的业务进行扩展
 */
class SelectableActivity : BaseActivity(){
    private lateinit var binding: ActivitySelectableBinding
    private lateinit var adapter: SelectableIAdapter

    @SuppressLint("StringFormatMatches")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivitySelectableBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        adapter = SelectableIAdapter(getSampleData())
        binding.recyclerView.adapter = adapter

        // 设置点击事件监听器
        adapter.setItemClickListener(object : OnItemsClickListener {
            override fun onHeaderClick(position: Int) {
                // 头部点击事件处理
                ToastUtil.showLong("头部被点击")
            }

            override fun onItemButtonClick(position: Int) {
                val currentItem = adapter.getItem(position) as? SelectableItem
                binding.tvCount.text = getString(R.string.title_count,  adapter.getSelectedItemCount())

                Logger.d("已选择列表数据：" + MyJson.toJson(adapter.getSelectedList()))
            }
        })

        binding.button1.setOnClickListener(){
            adapter.selectAll()
            binding.tvCount.text = getString(R.string.title_count,  adapter.getSelectedItemCount())

            Logger.d("已选择列表数据：" + MyJson.toJson(adapter.getSelectedList()))
        }

        binding.button2.setOnClickListener(){
            adapter.clearSelection()
            binding.tvCount.text = getString(R.string.title_count,  adapter.getSelectedItemCount())

            Logger.d("已选择列表数据：" + MyJson.toJson(adapter.getSelectedList()))
        }
    }

    // 这个方法用于生成示例数据，请根据您的需求替换成自己的数据
    private fun getSampleData(): List<MultiItemEntity> {
        val data = mutableListOf<MultiItemEntity>()
        // 显示头部信息
        data.add(SelectableItem("Header", "Header Title", false, true, null))
        // 添加底部数据
        for (i in 1..50) {
            data.add(SelectableItem("Item $i", "Name $i", false, false, null))
        }

        return data
    }
}